package com.learn.algorithm_237;

/**
 * 237. 删除链表中的节点
 * https://leetcode-cn.com/problems/delete-node-in-a-linked-list/
 *
 * @author gatts, 2020/8/22 23:27
 */
public class DeleteListNode {

    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        node.next = node1;
        node1.next = node2;
        node2.next = node3;

        node1.val = node1.next.val;
        node1.next = node1.next.next;

        System.out.println(node);
    }

    /**
     * 被删除节点是delNode，如果delNode.pre = delNode.next，就需要找到前一个节点，很麻烦
     * 不如直接把delNode属性替换为delNode.next的，这样就不用去找前一个节点了
      * @param delNode 被删除节点
     */
    public void deleteNode(ListNode delNode) {
        delNode.val = delNode.next.val;
        delNode.next = delNode.next.next;
    }

}

class ListNode{

    int val;
    ListNode next;

    public ListNode(int val){
        this.val = val;
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder();
        builder.append(val);
        ListNode next = this.next;

        while (next != null){
            builder.append(" -> ").append(next.val);
            next = next.next;
        }
        return builder.toString();
    }
}




